import React from 'react';
import wangEditor from 'wangeditor';
import * as conf from './config';
import { Input,Select,Spin,Button,Upload,Icon,message,Modal} from 'antd';

const props = {
  action: conf.upload,
  multiple: false,
  showUploadList: false,
  onChange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      // console.log(info.file, info.fileList);
      $("#cover").val(info.file.response);
      $('#uploadImg').show().attr('src',info.file.response)
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

class App extends React.Component {

  constructor(props){
    super(props);
    this.state={
      loading: false,
      classData:[],
      previewVisible: false,
      previewImage: '',
    }

  }

  componentDidMount() {
    this.editor();
    this.getClass();
  }

  /**
   * 获取分类
   */
  getClass=()=>{
    conf.request(conf.action.select,{
      table:'m1c',
      where:{state:0}
    }).then((result)=>{
      this.setState({
        classData:result.data
      })
    })
  };

  /**
   * 实例化编辑器
   */
  editor=()=>{
    // 阻止输出log
    wangEditor.config.printLog = false;
    let editor = new wangEditor('editor');
    // 上传图片
    editor.config.uploadImgUrl = conf.upload;

    // 设置 headers
    editor.config.uploadHeaders = {
      'Accept' : 'text/x-json'
    };
    editor.create();
  };

  /**
   * class下拉选择框
   * @param value
   */
  handleChangeClass=(value)=>{
    $('#classId').val(value);
  };

  /**
   * submit 提交操作
   */
  submit=()=>{
    let params = {
      table:'m1',
      title:$('#name').val(),
      content:$('#editor').html(),
      picture:$('#cover').val(),
      recommend:false,
      relation:{    //关联分类
        table:'m1c',
        where:{_id:$('#classId').val()}
      }
    };
    if($.isEmptyObject(params.name)||$.isEmptyObject($('#classId').val())||$.isEmptyObject(params.content)||$.isEmptyObject(params.cover)){
      conf.tips('error','操作失败!','字段不能为空');
    }else{
      this.add(params);
    }
  };

  /**
   * 添加操作
   * @param params
   */
  add=(params={})=>{
    this.setState({ loading: true });
    conf.request(conf.action.add,params).then((result)=>{
      conf.tips(result);
      this.setState({
        loading: false
      });
    })
  };

  /**
   * 关闭弹出层
   */
  handleCancel = () => this.setState({ previewVisible: false });

  //图片预览
  imgOnClick=(e)=>{
    let self = $(e.target);
    this.setState({
      previewImage:self.attr('src'),
      previewVisible:true,
    });
  };

  render() {
    const { previewVisible, previewImage } = this.state;
    //类型
    let classData = this.state.classData;
    const Class = [];
    for (let i = 0; i < classData.length; i++) {
      Class.push(<Option key={classData[i]._id}>{classData[i].name}</Option>);
    }
    return (
      <Spin spinning={this.state.loading} tip="Loading...">
        <div id="add">
          <div className="row">
            <div className="title">图片名称：</div>
            <Input id="name" placeholder="图片名称" />
          </div>
          <div className="row">
            <div className="title">选择分类：</div>
            <Select
              showSearch
              style={{ width: 200 }}
              placeholder="请选择分类"
              optionFilterProp="children"
              onChange={this.handleChangeClass}
              filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
              {Class}
            </Select>
            <input type="hidden" id="classId"/>
          </div>
          <div className="row">
            <div className="title">设置封面：</div>
            <Input id="cover" placeholder="选择封面"/>
            <Upload {...props}>
              <Button style={{width:100,marginLeft:15}}>
                <Icon type="upload" /> upload
              </Button>
            </Upload>
            <div className="pictureList">
              <img id="uploadImg" onClick={this.imgOnClick.bind(this)} src="http://image.ecs001.com/images/common/background.png" />
            </div>
            {/*图片弹出层*/}
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </div>
          <div className="row">
            <div style={{paddingLeft:20}}>编辑内容：</div>
          </div>
          <div className="row" style={{paddingLeft:20}}>
            <div id="editor"></div>
          </div>
          <div className="row">
            <Button type='primary' onClick={this.submit} style={{marginLeft:20}}>立即添加</Button>
          </div>
        </div>
      </Spin>
    );
  }
}


export default App;